from typing import Any, List
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session

from app.api import deps
from app.schemas import airplane
from app.database.models.erp import Airplane
from app.database.models.base import User

router = APIRouter()

@router.get("/", response_model=List[airplane.Airplane])
def list_airplanes(
    db: Session = Depends(deps.get_db),
    skip: int = 0,
    limit: int = 100,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取飞机型号列表"""
    airplanes = db.query(Airplane).offset(skip).limit(limit).all()
    return airplanes

@router.post("/", response_model=airplane.Airplane)
def create_airplane(
    *,
    db: Session = Depends(deps.get_db),
    airplane_in: airplane.AirplaneCreate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """创建新飞机型号"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    # 检查型号是否已存在
    if db.query(Airplane).filter(Airplane.PlaneModel == airplane_in.PlaneModel).first():
        raise HTTPException(
            status_code=400,
            detail="Airplane model already registered"
        )
    
    # 验证座位数
    if airplane_in.MinSeatCount > airplane_in.MaxSeatCount:
        raise HTTPException(
            status_code=400,
            detail="MinSeatCount cannot be greater than MaxSeatCount"
        )
    
    airplane = Airplane(**airplane_in.dict())
    db.add(airplane)
    db.commit()
    db.refresh(airplane)
    return airplane

@router.get("/{airplane_id}", response_model=airplane.Airplane)
def get_airplane(
    airplane_id: int,
    db: Session = Depends(deps.get_db),
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """获取特定飞机型号信息"""
    airplane = db.query(Airplane).filter(Airplane.AirplaneId == airplane_id).first()
    if not airplane:
        raise HTTPException(status_code=404, detail="Airplane not found")
    return airplane

@router.put("/{airplane_id}", response_model=airplane.Airplane)
def update_airplane(
    *,
    db: Session = Depends(deps.get_db),
    airplane_id: int,
    airplane_in: airplane.AirplaneUpdate,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """更新飞机型号信息"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    airplane = db.query(Airplane).filter(Airplane.AirplaneId == airplane_id).first()
    if not airplane:
        raise HTTPException(status_code=404, detail="Airplane not found")
    
    update_data = airplane_in.dict(exclude_unset=True)
    
    # 如果更新座位数，验证最小座位数不大于最大座位数
    if 'MinSeatCount' in update_data or 'MaxSeatCount' in update_data:
        min_seats = update_data.get('MinSeatCount', airplane.MinSeatCount)
        max_seats = update_data.get('MaxSeatCount', airplane.MaxSeatCount)
        if min_seats > max_seats:
            raise HTTPException(
                status_code=400,
                detail="MinSeatCount cannot be greater than MaxSeatCount"
            )
    
    for field, value in update_data.items():
        setattr(airplane, field, value)
    
    db.add(airplane)
    db.commit()
    db.refresh(airplane)
    return airplane

@router.delete("/{airplane_id}")
def delete_airplane(
    *,
    db: Session = Depends(deps.get_db),
    airplane_id: int,
    current_user: User = Depends(deps.get_current_active_user)
) -> Any:
    """删除飞机型号"""
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="Not enough permissions")
    
    airplane = db.query(Airplane).filter(Airplane.AirplaneId == airplane_id).first()
    if not airplane:
        raise HTTPException(status_code=404, detail="Airplane not found")
    
    db.delete(airplane)
    db.commit()
    return {"ok": True} 